package com.sxhuayuan.parking.controller.open;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.utils.SignatureUtils;
import com.sxhuayuan.parking.utils.SpringUtils;

/**
 * api统一返回消息对象
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResp {

	public enum Status {
		OK, FAIL
	}

	private Integer status;

	private String msg;

	private String sign;

	private String timestamp;

	private String nonce;

	private Object data;

	public final Integer getStatus() {
		return status;
	}

	public final void setStatus(Integer status) {
		this.status = status;
	}

	public final String getMsg() {
		return msg;
	}

	public final void setMsg(String msg) {
		this.msg = SpringUtils.getMessage(msg);
	}

	public final String getSign() {
		return sign;
	}

	public final void setSign(String sign) {
		this.sign = sign;
	}

	public final String getTimestamp() {
		return timestamp;
	}

	public final void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public final String getNonce() {
		return nonce;
	}

	public final void setNonce(String nonce) {
		this.nonce = nonce;
	}

	public final Object getData() {
		return data;
	}

	public final void setData(Object data) {
		this.data = data;
	}

	public ApiResp(Status status, String msg, Object data) {
		super();
		this.status = status.ordinal();
		this.msg = SpringUtils.getMessage(msg);
		this.data = data;
	}

	public ApiResp sign(String key) {
		this.setNonce(RandomStringUtils.randomAlphanumeric(8));
		this.setTimestamp(String.valueOf(System.currentTimeMillis()));
		Map<String, Object> map = new HashMap<>();
		map.put("status", String.valueOf(this.status));
		map.put("nonce", String.valueOf(this.nonce));
		map.put("timestamp", this.timestamp);
		if (this.data != null)
			map.put("data", JSON.toJSONString(this.data));
		this.sign = SignatureUtils.signMd5(map, "key", key);
		return this;
	}

	public static ApiResp success() {
		ApiResp resp = new ApiResp(Status.OK, SpringUtils.getMessage(Message.COMMON_SUCCESS), null);
		return resp;
	}

	public static ApiResp success(String msg) {
		ApiResp resp = new ApiResp(Status.OK, msg, null);
		return resp;
	}

	public static ApiResp success(Object data) {
		return new ApiResp(Status.OK, SpringUtils.getMessage(Message.COMMON_SUCCESS), data);
	}

	public static ApiResp success(String msg, Object data) {
		return new ApiResp(Status.OK, msg, data);
	}

	public static ApiResp error(String msg) {
		return new ApiResp(Status.FAIL, msg, null);
	}

	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}
}
